package com.example.batch.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableConfigurationProperties({MultiDataSourceProperties.class})
public class DynamicDataSourceConfig {

    @Bean
    @Primary
    public DataSource dynamicDataSource(MultiDataSourceProperties properties) {
        DynamicRoutingDataSource dynamicDataSource = new DynamicRoutingDataSource();
        
        Map<Object, Object> dataSources = new HashMap<>();
        properties.getSources().forEach((key, config) -> {
            DataSource dataSource = createDataSource(config);
            dataSources.put(key, dataSource);
        });
        
        // 设置默认数据源
        dynamicDataSource.setDefaultTargetDataSource(
            dataSources.get(properties.getPrimary()));
        dynamicDataSource.setTargetDataSources(dataSources);
        
        return dynamicDataSource;
    }
    
    @Bean
    public PersistenceProviderResolver persistenceProviderResolver(
            MultiDataSourceProperties properties) {
        return new DynamicPersistenceProviderResolver(properties);
    }
    
    private DataSource createDataSource(DataSourceProperties config) {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(config.getUrl());
        dataSource.setUsername(config.getUsername());
        dataSource.setPassword(config.getPassword());
        dataSource.setDriverClassName(config.getDriverClassName());
        
        // 应用额外的数据源配置
        config.getProperties().forEach(dataSource::addDataSourceProperty);
        
        return dataSource;
    }
} 